package com.caine.tc.tool;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: CaineZhu
 * @Description: 为什么不用fastjson? 因为坑太多,还是jackson稳
 * @Date: Created in 15:55 2020/6/24
 * @Modified By:
 */
public class JSONTool {
    private static ObjectMapper mapper;

    static {
        mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * String转对象
     * @param val
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T parseObject(String val, Class<T> clazz) {
        try {
            return mapper.readValue(val, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JsonProcessingException 异常", e.getCause());
        }
    }

    /**
     * object to jsonstring
     *
     * @param obj
     * @return string
     */
    public static String toJSONString(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSONTools toJSONString 异常:", e.getCause());
        }
    }

    /**
     * 对象转map
     * @param t
     * @param <T>
     * @return
     */
    public static <T> Map<String, Object> obj2Map(T t){
        Field[] declaredFields = t.getClass().getDeclaredFields();
        Map<String, Object> map = new HashMap<>();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            String name = declaredField.getName();
            if (!name.isEmpty()) {
                try {
                    map.put(name, declaredField.get(t));
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("IllegalAccessException 异常:", e.getCause());
                }
            }
        }
        return map;
    }
}
